import 'package:flutter/material.dart';
import 'package:flutter_rfid_dmo/model/tag.dart';

class DialogUtils {
  static Future<String?> showWriteEpcDialog(
      BuildContext context, String epc) async {
    final formKey = GlobalKey<FormState>();
    final odfController = TextEditingController(text: '1');
    final trayController = TextEditingController(text: '1');
    final portController = TextEditingController(text: '1');
    int patchType = 1; // 0=SC, 1=FC, 2=SC+FC

    // 默认类型
    int tabIndex = 0; // 0=端口标签, 1=插头标签
    String epcStr = epc;
    var model = decodeEPC(epc);

    if (model is PatchCordTag) {
      tabIndex = 1;
      odfController.text = model.odfNo.toString();
      trayController.text = model.trayNo.toString();
      portController.text = model.portNo.toString();
      patchType = model.type;
    } else if (model is PortTag) {
      tabIndex = 0;
      odfController.text = model.odfNo.toString();
      trayController.text = model.trayNo.toString();
      portController.text = model.portNo.toString();
    }

    void updateEpcStr(StateSetter setState) {
      final odf = int.tryParse(odfController.text) ?? 1;
      final tray = int.tryParse(trayController.text) ?? 1;
      final port = int.tryParse(portController.text) ?? 1;
      if (tabIndex == 0) {
        epcStr = generatePortEpc(odfNo: odf, trayNo: tray, portNo: port);
      } else {
        epcStr = generatePlugEpc(
          odfNo: odf,
          trayNo: tray,
          portNo: port,
          type: patchType,
        );
      }
      setState(() {});
    }

    var result = await showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: SizedBox(
                height: 48,
                child: DefaultTabController(
                  length: 2,
                  initialIndex: tabIndex,
                  child: TabBar(
                    onTap: (idx) {
                      tabIndex = idx;
                      updateEpcStr(setState);
                    },
                    tabs: const [
                      Tab(text: '端口标签'),
                      Tab(text: '插头标签'),
                    ],
                  ),
                ),
              ),
              content: Form(
                key: formKey,
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextFormField(
                        controller: odfController,
                        decoration:
                            const InputDecoration(labelText: 'ODM编号（1-16）'),
                        keyboardType: TextInputType.number,
                        validator: (value) => validateNumberInput(
                          value: value,
                          label: 'ODM编号',
                          min: 1,
                          max: 16,
                        ),
                        onChanged: (_) => updateEpcStr(setState),
                      ),
                      TextFormField(
                        controller: trayController,
                        decoration:
                            const InputDecoration(labelText: '托盘号（1-16）'),
                        keyboardType: TextInputType.number,
                        validator: (value) => validateNumberInput(
                          value: value,
                          label: '托盘号',
                          min: 1,
                          max: 16,
                        ),
                        onChanged: (_) => updateEpcStr(setState),
                      ),
                      TextFormField(
                        controller: portController,
                        decoration:
                            const InputDecoration(labelText: '端口号（1-12）'),
                        keyboardType: TextInputType.number,
                        validator: (value) => validateNumberInput(
                          value: value,
                          label: '端口号',
                          min: 1,
                          max: 12,
                        ),
                        onChanged: (_) => updateEpcStr(setState),
                      ),
                      if (tabIndex == 1)
                        Column(
                          children: [
                            const SizedBox(height: 8),
                            const Align(
                              alignment: Alignment.centerLeft,
                              child: Text('类型',
                                  style:
                                      TextStyle(fontWeight: FontWeight.bold)),
                            ),
                            Wrap(
                              children: [
                                for (var opt in [
                                  {'label': 'SC', 'value': 1},
                                  {'label': 'FC', 'value': 2},
                                  {'label': 'SC+FC', 'value': 3},
                                ])
                                  SizedBox(
                                    width: 100,
                                    child: RadioListTile<int>(
                                      dense: true,
                                      contentPadding: EdgeInsets.zero,
                                      title: Transform.translate(
                                        offset: const Offset(-20, 0),
                                        child: Text(opt['label'] as String,
                                            style: const TextStyle(
                                                color: Colors.blueGrey)),
                                      ),
                                      groupValue: patchType,
                                      value: opt['value'] as int,
                                      activeColor: Colors.green,
                                      onChanged: (v) {
                                        patchType = v!;
                                        updateEpcStr(setState);
                                      },
                                    ),
                                  ),
                              ],
                            ),
                          ],
                        ),
                      Padding(
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Text(
                          epcStr,
                          style: const TextStyle(
                              color: Colors.blue, fontWeight: FontWeight.bold),
                        ),
                      )
                    ],
                  ),
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    if (formKey.currentState?.validate() ?? false) {
                      Navigator.pop(context, epcStr);
                    }
                  },
                  child: const Text('写入'),
                ),
              ],
            );
          },
        );
      },
    );
    return result;
  }
}

String generatePlugEpc({
  required int odfNo,
  required int trayNo,
  required int portNo,
  required int type, // 1=SC, 2=FC
}) {
  final odfStr = odfNo.toHex();
  final trayStr = trayNo.toHex();
  final portStr = portNo.toHex();
  final typeStr = type.toHex();
  return 'E1$odfStr$trayStr$portStr$typeStr';
}

String generatePortEpc({
  required int odfNo,
  required int trayNo,
  required int portNo,
}) {
  // ODF编号4位，托盘号4位，端口号4位
  final odfStr = odfNo.toHex();
  final trayStr = trayNo.toHex();
  final portStr = portNo.toHex();
  return 'A1$odfStr$trayStr$portStr';
}

String? validateNumberInput({
  required String? value,
  required String label,
  required int min,
  required int max,
}) {
  final v = int.tryParse(value ?? '');
  if (v == null) return '请输入数字';
  if (v < min || v > max) return '$label范围$min-$max';
  return null;
}
